package com.ccsoft.zknote.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonUtils {

    /**
     *     使用示例
     *     @Test
     *     public void test01() throws JsonProcessingException {
     *         Person p = new Person("chanchaw",36);
     *         String jsonString = JsonUtils.toString(p);
     *         System.out.println("对象序列化后是：" + jsonString);
     *
     *         Person p1 = JsonUtils.toObject(jsonString,Person.class);
     *         System.out.println("反序列化后是：" + p1.toString());
     *     }
     */
    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 将对象转换为 json 字符串
     * @param obj 任何基本类型或者引用类型
     * @return 返回 json 字符串
     * @throws JsonProcessingException
     */
    public static String toString(Object obj) throws JsonProcessingException {
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        return mapper.writeValueAsString(obj);
    }

    /**
     * 将字符串反序列化为对象
     * @param jsonString 对象的 json 字符串
     * @param c 返回的对象的类类型
     * @param <T> 返回的对象的类型
     * @return 返回指定类型的对象
     * @throws JsonProcessingException
     */
    public static <T>T toObject(String jsonString,Class<T> c) throws JsonProcessingException {
        return (T) mapper.readValue(jsonString,c);
    }
}
